package visualcbir.visualstructures;

import java.util.Observable;
import visualcbir.IBackStructureView;
import visualcbir.Model;
import visualcbir.ModelComposed;
import visualcbir.ViewComposed;
import visualcbir.util.VSUtils;
import visualcbir.node.ModelNode;
import visualcbir.node.ViewNode;

/**
 *
 * @author sheila
 */
    public class VSGrid extends ViewComposed{

    public VSGrid(ModelComposed oModel, int piNumSubviews){     super(oModel,piNumSubviews);    }

    @Override
    public IBackStructureView makeBackStructureView() {     return null;    }

    /*
     * As the first update gets 0 from viewDimension, the dimension used is the jpanel visible dimension.
     * Computes mathematical and trigonometrical data needed to draw each object in
     * the view.
     */
    @Override
    public void update(Observable o, Object arg) {
        int imageBorder = (int) Math.round(10*this.getScaleFactor() );
        double scaleFactorSubViews = this.getScaleFactor()*0.8;
        int dAvailableWidth;
        System.out.println("this.getCenterPoint().x"+this.getCenterPoint().x);
        // if temporal para diferenciar se é vista unica ou subview de outra
        if(this.getScaleFactor()>0.79)
            dAvailableWidth = this.getCenterPoint().x * 2;
        else
            dAvailableWidth = (int) ((int) 500 * this.getScaleFactor());
        double dCellLength  =  (VSUtils.getRealImageScaleFactor(scaleFactorSubViews) + imageBorder*2);

        int numCols = (int)Math.floor(dAvailableWidth/dCellLength);
        if(numCols==0)  return;
        int numRows =  (int)Math.ceil( (double)this.iNumSubviews/numCols );
        int val = (int)Math.round(dCellLength/2);
        int x = this.getCenterPoint().x-(dAvailableWidth/2)+val, x0=x, y= this.getCenterPoint().y;// a y falta restar a available y. tarde
        int iNodeNumber=0;

        for( int j=0; j < numRows; j++, y+=dCellLength, x=x0){
            for(int i = 0; i < numCols && iNodeNumber < this.iNumSubviews ; i++, x+=dCellLength) {
                super.getView(iNodeNumber).setCenterPoint((int)Math.round(x), (int)Math.round(y));
                super.getView(iNodeNumber).setScaleFactor(scaleFactorSubViews);
                iNodeNumber++;                
            }
        }

        super.setViewDimension( dAvailableWidth, y-this.getCenterPoint().y );
        super.update(o,arg);// updating all subviews.
    }    

    @Override
    public void addView(Model oModelAdded) {
       if(oModelAdded instanceof ModelNode)
            super.addView(new ViewNode((ModelNode)oModelAdded));
    }
}
